package com.suke.czx.modules.tb.controller;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.suke.czx.authentication.detail.CustomUserDetailsUser;
import com.suke.czx.common.annotation.AuthIgnore;
import com.suke.czx.modules.tb.entity.TbLikes;
import com.suke.czx.modules.tb.entity.TbUserFavorite;
import com.suke.czx.modules.tb.service.TbLikesService;
import com.suke.czx.modules.tb.service.TbUserFavoriteService;
import com.suke.czx.modules.tb.vo.ProductQueryVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.*;
import com.suke.czx.modules.tb.entity.TbProduct;
import com.suke.czx.modules.tb.service.TbProductService;
import com.suke.czx.common.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import com.suke.czx.common.annotation.SysLog;
import com.suke.czx.common.base.AbstractController;

import javax.annotation.Resource;


/**
 * 商品表
 *
 * @author developer
 * @email developer@163.com
 * @date 2025-05-14 21:06:11
 */
@RestController
@AllArgsConstructor
@RequestMapping("/tb/product")
@Api(value = "TbProductController", tags = "商品表")
public class TbProductController extends AbstractController {
    private final TbProductService tbProductService;

    @Resource
    private TbLikesService tbLikesService;
    @Resource
    private TbUserFavoriteService tbUserFavoriteService;

    // 发布商品
    @ApiOperation(value = "发布商品")
    @SysLog("发布商品")
    @PostMapping("/publish")
    public R publish(@RequestBody TbProduct tbProduct) {
        String userId = getUserId();
        if (StringUtils.isBlank(userId)) {
            return R.error("未登录");
        }
        // 判断图片
        if (StringUtils.isBlank(tbProduct.getImageUrls())) {
            return R.error("请上传商品图片");
        }
        if (StringUtils.isBlank(tbProduct.getTitle())) {
            return R.error("请填写商品标题");
        }
        if (StringUtils.isBlank(tbProduct.getDescription())) {
            return R.error("请填写商品描述");
        }
        if (tbProduct.getPrice() == null || tbProduct.getPrice().compareTo(BigDecimal.ZERO) <= 0) {
            return R.error("价格不能小于0");
        }
        if (StringUtils.isBlank(tbProduct.getLocation())) {
            return R.error("请填写发货地区");
        }

        if (null != tbProduct.getId() && 0L != tbProduct.getId()) {
            TbProduct product = tbProductService.getById(tbProduct.getId());
            if (product == null || !product.getUserId().equals(userId)) {
                return R.error("商品不存在或无权限");
            }
            product.setImageUrls(tbProduct.getImageUrls());
            product.setTitle(tbProduct.getTitle());
            product.setDescription(tbProduct.getDescription());
            product.setPrice(tbProduct.getPrice());
            product.setLocation(tbProduct.getLocation());
            boolean b = tbProductService.updateById(product);
            return R.ok().setData(product);
        }

        tbProduct.setUserId(userId);
        boolean save = tbProductService.save(tbProduct);
        return R.ok().setData(tbProduct);
    }

    // 我发布的
    @ApiOperation(value = "我发布的")
    @PostMapping("/myPublish")
    public R myPublish(@RequestBody Map<String,Object> params) {
        String userId = getUserId();
        if (StringUtils.isBlank(userId)) {
            return R.error("未登录");
        }
        LambdaQueryWrapper<TbProduct> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TbProduct::getUserId, userId);
        List<TbProduct> products = tbProductService.list(queryWrapper);
        return R.ok().setData(products);
    }

    // 下架
    @ApiOperation(value = "下架")
    @PostMapping("/delisted/{id}")
    public R delisted(@PathVariable("id") Long id) {
        // 1. 校验ID合法性（Spring Validation）
        if (id == null || id < 1) {
            return R.error("非法ID");
        }
        // 2. 获取当前用户ID（你的getUserId()）
        String userId = getUserId();
        if (StringUtils.isBlank(userId)) {
            return R.error("未登录");
        }
        // 3. 检查是否已下架
        TbProduct product = tbProductService.getById(id);
        if (product == null || !product.getUserId().equals(userId)) {
            return R.error("商品不存在或无权限");
        }
        product.setStatus("delisted");
        boolean update = tbProductService.updateById(product);
        return R.ok().setData(product);
    }

    @ApiOperation(value = "上架")
    @PostMapping("/available/{id}")
    public R available(@PathVariable("id") Long id) {
        // 1. 校验ID合法性（Spring Validation）
        if (id == null || id < 1) {
            return R.error("非法ID");
        }
        // 2. 获取当前用户ID（你的getUserId()）
        String userId = getUserId();
        if (StringUtils.isBlank(userId)) {
            return R.error("未登录");
        }
        // 3. 检查
        TbProduct product = tbProductService.getById(id);
        if (product == null || !product.getUserId().equals(userId)) {
            return R.error("商品不存在或无权限");
        }
        product.setStatus("available");
        boolean update = tbProductService.updateById(product);
        return R.ok().setData(product);
    }



    /**
     * 推荐商品
     */
    @ApiOperation(value = "推荐商品")
    @PostMapping("/recommend")
    public R recommend(@RequestBody ProductQueryVO productQueryVO) {
        productQueryVO.setUserId(null);
        try {
            String userId = getUserId();
            if(StringUtils.isBlank(userId)){
                System.out.println(userId);
            }
            productQueryVO.setUserId(userId);
            //TODO 根据用户喜好推荐
            return R.ok().setData(tbProductService.recommendList(productQueryVO));
        } catch (java.lang.ClassCastException e){
        }
        return R.ok().setData(tbProductService.recommendList(productQueryVO));
    }

    @ApiOperation(value = "点赞")
    @PostMapping("/like/{id}")
    public R like(@PathVariable("id") Long id) {
        // 1. 校验ID合法性（Spring Validation）
        if (id == null || id < 1) {
            return R.error("非法ID");
        }
        // 2. 获取当前用户ID（你的getUserId()）
        String userId = getUserId();
        if (StringUtils.isBlank(userId)) {
            return R.error("未登录");
        }
        // 3. 检查是否已点赞
        boolean exists = tbLikesService.lambdaQuery()
                .eq(TbLikes::getUserId, userId)
                .eq(TbLikes::getProductId, id)
                .exists();

        // 4. 存在则取消点赞，不存在则新增
        if (exists) {
            tbLikesService.lambdaUpdate()
                    .eq(TbLikes::getUserId, userId)
                    .eq(TbLikes::getProductId, id)
                    .remove();
            return R.ok("取消点赞成功");
        } else {
            tbLikesService.save(new TbLikes(userId, id));
            return R.ok("点赞成功");
        }
    }

    @ApiOperation(value = "收藏")
    @PostMapping("/favorite/{id}")
    public R favorite(@PathVariable("id") Long id) {
        // 1. 校验ID合法性（Spring Validation）
        if (id == null || id < 1) {
            return R.error("非法ID");
        }
        // 2. 获取当前用户ID（你的getUserId()）
        String userId = getUserId();
        if (StringUtils.isBlank(userId)) {
            return R.error("未登录");
        }
        // 3. 检查是否已收藏
        boolean exists = tbUserFavoriteService.lambdaQuery()
                .eq(TbUserFavorite::getUserId, userId)
                .eq(TbUserFavorite::getProductId, id)
                .exists();

        // 4. 存在则取消收藏，不存在则新增
        if (exists) {
            tbUserFavoriteService.lambdaUpdate()
                    .eq(TbUserFavorite::getUserId, userId)
                    .eq(TbUserFavorite::getProductId, id)
                    .remove();
            return R.ok("取消收藏成功");
        } else {
            tbUserFavoriteService.save(new TbUserFavorite(userId, id));
            return R.ok("收藏成功");
        }
    }


    // 商品详情
    @ApiOperation(value = "商品详情")
    @AuthIgnore
    @GetMapping("/{id}")
    public R detail(@PathVariable("id") Long id) {
        return R.ok().setData(tbProductService.getDetailById(id));
    }
//511016871
    /**
     * 列表
     */
    @ApiOperation(value = "商品表列表")
    @GetMapping("/list")
    public R list(@RequestParam Map<String, Object> params) {
        String username = getUser().getUsername();
        String userId = getUserId();
        //查询列表数据
        LambdaQueryWrapper<TbProduct> queryWrapper = new LambdaQueryWrapper<>();
        final String keyword = mpPageConvert.getKeyword(params);
        if (StrUtil.isNotEmpty(keyword)) {
            queryWrapper.like(TbProduct::getTitle, keyword);
        }
        if(!"admin".equals(username)){
            queryWrapper.eq(TbProduct::getUserId, userId);
        }
        IPage<TbProduct> listPage = tbProductService.page(mpPageConvert.<TbProduct>pageParamConvert(params), queryWrapper);
        return R.ok().setData(listPage);
    }

    /**
     * 新增商品表
     */
    @ApiOperation(value = "新增商品表数据")
    @SysLog("新增商品表数据")
    @PostMapping()
    public R save(@RequestBody TbProduct tbProduct) {
        tbProductService.save(tbProduct);
        return R.ok();
    }


    /**
     * 修改
     */
    @ApiOperation(value = "修改商品表数据")
    @SysLog("修改商品表数据")
    @PutMapping()
    public R update(@RequestBody TbProduct tbProduct) {
        tbProductService.updateById(tbProduct);
        return R.ok();
    }


    /**
     * 删除
     */
    @ApiOperation(value = "删除商品表数据")
    @SysLog("删除商品表数据")
    @DeleteMapping()
    public R delete(@RequestBody TbProduct tbProduct) {
        tbProductService.removeById(tbProduct.getId());
        return R.ok();
    }

}
